import { Component, OnInit } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { Product } from '../../api/product';
import { ProductService } from '../../service/productservice';
import { Subscription } from 'rxjs';
import { ConfigService } from '../../service/app.config.service';
import { AppConfig } from '../../api/appconfig';
import { StatisticsService } from 'src/app/service/statistics.service';
import { HomeService } from 'src/app/service/home.service';
import { Chart } from 'chart.js';

//import { select, Store } from '@ngrx/store';
//import { getToken } from 'src/app/store/user/user.reducer';
@Component({
    selector: 'app-home-page',
    templateUrl: './home-page.component.html',
    styleUrls: ['./home-page.component.scss'],
})
export class HomePageComponent implements OnInit {
    counts: any = {
        total: 0,
        installedCounts: 0,
        unInstallCounts: 0,
    };

    totalcounts = {
        num: [],
        // twenty: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // nineteen: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // eighteen: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        sum: 0,
    };

    citys = [];

    consumption = [];

    tableData: any[];

    currentYear: any;

    currentYear2: any;

    currentYear3: any;

    items: MenuItem[];

    products: Product[];

    chartData: any;

    chartOptions: any;

    chartData2: any;

    chartOptions2: any;

    chartData3: any;

    chartOptions3: any;

    subscription: Subscription;

    config: AppConfig;

    year1: any;

    year2: any;

    year3: any;

    constructor(
        private productService: ProductService,
        public configService: ConfigService,
        public statisticsService: StatisticsService, //private store:Store
        private homeService: HomeService
    ) {}

    ngOnInit() {
        //console.log(this.store.pipe(select(getToken)).subscribe(console.log))
        /*async () => {
            const res = await fetchInstalled()
            console.log('message', res.message)
            if (res.code === '200') {
              this.counts = res.data
            }
        }*/
        this.currentYear = new Date();
        this.currentYear2 = new Date();
        this.currentYear3 = new Date();
        this.getLinePic();
        this.getCount();
        this.getTotalStatistics();
        this.getUserRank();
        this.getUserBar();
        this.subscription = this.configService.configUpdate$.subscribe(
            (config) => {
                this.config = config;
                this.updateChartOptions();
            }
        );
        this.items = [
            { label: 'Add New', icon: 'pi pi-fw pi-plus' },
            { label: 'Remove', icon: 'pi pi-fw pi-minus' },
        ];
    }

    updateChartOptions() {
        if (this.config.dark) this.applyDarkTheme();
        else this.applyLightTheme();
    }

    applyDarkTheme() {
        this.chartOptions = {
            barValueSpacing: 5,
            plugins: {
                legend: {
                    labels: {
                        color: '#ebedef',
                    },
                },
            },
            scales: {
                xAxes: {
                    ticks: {
                        color: '#ebedef',
                    },
                    grid: {
                        color: 'rgba(160, 167, 181, .3)',
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'hhhh',
                    },
                },
                yAxes: {
                    ticks: {
                        color: '#ebedef',
                    },
                    grid: {
                        color: 'rgba(160, 167, 181, .3)',
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'ddss',
                    },
                },
            },
        };
    }

    applyLightTheme() {
        this.chartOptions = {
            plugins: {
                legend: {
                    labels: {
                        color: '#495057',
                    },
                },
            },
            scales: {
                xAxes: {
                    ticks: {
                        color: '#495057',
                    },
                    grid: {
                        color: '#ebedef',
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'hhhh',
                    },
                },
                yAxes: {
                    ticks: {
                        color: '#495057',
                    },
                    grid: {
                        color: '#ebedef',
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'hhhh',
                    },
                },
            },
        };
    }
    async getCount() {
        const res = await this.statisticsService.fetchInstalled();
        //console.log('message', res.message);
        if (res.code === '200') {
            this.counts = res.data;
        }
    }
    async getLinePic() {
        const current = this.currentYear.getFullYear();
        const res1 = await this.homeService.fetchMounthCostByYear({
            year: current,
        });
        const res2 = await this.homeService.fetchMounthCostByYear({
            year: current - 1,
        });
        const res3 = await this.homeService.fetchMounthCostByYear({
            year: current - 2,
        });
        //console.log(res2);
        if (res1.code === '200' && res2.code === '200' && res3.code === '200') {
            this.year1 = res1.data.map((item) => item.volume);
            this.year2 = res2.data.map((item) => item.volume);
            this.year3 = res3.data.map((item) => item.volume);
        }
        this.chartData3 = {
            labels: [
                '1月',
                '2月',
                '3月',
                '4月',
                '5月',
                '6月',
                '7月',
                '8月',
                '9月',
                '10月',
                '11月',
                '12月',
            ],
            datasets: [
                {
                    type: 'line',
                    label: this.currentYear.getFullYear() + '年',
                    data: this.year1,
                    fill: false,
                    backgroundColor: '#00bb7e',
                    borderColor: '#00bb7e',
                },
                {
                    type: 'line',
                    label: this.currentYear.getFullYear() - 1 + '年',
                    data: this.year2,
                    fill: false,
                    backgroundColor: '#42A5F5',
                    borderColor: '#42A5F5',
                },
                {
                    type: 'line',
                    label: this.currentYear.getFullYear() - 2 + '年',
                    data: this.year3,
                    fill: false,
                    backgroundColor: '#FFA726',
                    borderColor: '#FFA726',
                },
            ],
        };
        //console.log(this.year2);
    }
    async getTotalStatistics() {
        const res = await this.homeService.fetchMounthCostByYear({
            year: this.currentYear2.getFullYear(),
        });
        if (res.code === '200') {
            this.totalcounts.num = res.data.map((item) => item.volume);
            this.totalcounts.sum = res.data.reduce((last, item) => {
                return (last || 0) + item.volume;
            }, 0);
        }
        this.chartData2 = {
            labels: [
                '1月',
                '2月',
                '3月',
                '4月',
                '5月',
                '6月',
                '7月',
                '8月',
                '9月',
                '10月',
                '11月',
                '12月',
            ],
            datasets: [
                {
                    type: 'bar',
                    label: this.currentYear2.getFullYear() + '年每月用水量',
                    data: this.totalcounts.num,
                    fill: false,
                    backgroundColor: '#00bb7e',
                    borderColor: '#00bb7e',
                    tension: 0.4,
                },
            ],
        };
    }
    async getUserRank() {
        let res = await this.homeService.fetchCostRank({
            year: new Date().getFullYear() - 1,
        });
        if (res.code === '200') {
            // tableData.value = list.addAttrToEach('person', nameGenerator)
            this.tableData = res.data;
        }
    }
    async getUserBar() {
        const res = await this.homeService.fetchWaterCostByYear({
            year: this.currentYear3.getFullYear(),
        });
        if (res.code === '200') {
            this.citys = res.data.map((item) => item.applicantName);
            this.consumption = res.data.map((item) => item.volume);
        }
        this.chartData = {
            labels: this.citys,
            datasets: [
                {
                    label: '用户用水情况',
                    data: this.consumption,
                    fill: false,
                    barThickness: 30,
                    backgroundColor: [
                        '#2f4860',
                        '#ff6384',
                        '#36a2eb',
                        '#cc65fe',
                        '#ffce56',
                    ],
                    borderColor: [
                        '#2f4860',
                        '#ff6384',
                        '#36a2eb',
                        '#cc65fe',
                        '#ffce56',
                    ],
                },
            ],
        };
        console.log(this.citys);
        console.log(this.consumption);
    }
}
